# qwen2.5-vl 无法识别音频

import requests
import json
from typing import Optional

DIR = "/Users/michael/codes_ai/python/ai_demo_nlp_python/files/"
FILE_01 = "%stest.wav" % DIR

def qwen_vl_recognize(
        audio_path: str,
        ollama_url: str = "http://localhost:11434/api/generate",
        model: str = "qwen2.5vl:3b",
        prompt: str = "请识别这段音频的内容:",
        max_tokens: int = 1000,
        stream: bool = False,
) -> Optional[str]:
    """
    调用 Qwen-VL2.5:3B 进行语音识别

    Args:
        audio_path: 音频文件路径（支持 WAV/MP3）
        ollama_url: Ollama API 地址
        model: 模型名称
        prompt: 提示词
        max_tokens: 最大输出长度
        stream: 是否流式输出

    Returns:
        识别的文本结果（若失败返回 None）
    """
    try:
        # 1. 读取音频文件（需确保文件存在）
        with open(audio_path, "rb") as f:
            audio_bytes = f.read()

        # 2. 构造请求数据（Ollama 的 API 格式）
        data = {
            "model": model,
            "prompt": f"{prompt} [音频文件: {audio_path}]",
            "stream": stream,
            "max_tokens": max_tokens,
            # 部分模型支持直接传递文件，若报错可尝试 Base64 编码
            "files": [{"name": audio_path, "data": audio_bytes.hex()}]
        }

        # 3. 发送请求
        response = requests.post(
            ollama_url,
            headers={"Content-Type": "application/json"},
            data=json.dumps(data),
            timeout=60
        )
        response.raise_for_status()

        # 4. 解析响应（流式或非流式）
        if stream:
            full_response = ""
            for line in response.iter_lines():
                if line:
                    chunk = json.loads(line.decode("utf-8"))
                    full_response += chunk.get("response", "")
            return full_response.strip()
        else:
            result = response.json()
            return result.get("response", "").strip()

    except Exception as e:
        print(f"Error: {e}")
        return None


# 示例调用
if __name__ == "__main__":
    text_result = qwen_vl_recognize(FILE_01)
    if text_result:
        print("识别结果:", text_result)
    else:
        print("识别失败")